package com.tgy.studentmanagement.common;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tgy.studentmanagement.constant.CommonConsts;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import java.util.List;

/***
 * @ClassName: RPage
 * @Description: 分页返回
 * @Auther: tanggy3
 * @Date: 9:33 2023/4/13
 * @version : V1.0
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value = "RPage对象", description = "Page接口返回通用结构体")
public class RPage<T> extends R<T> {
    private static final long serialVersionUID = 1L;

    /**
     * 兼容旧代码属性，仅返回分页信息时有效
     */
    @ApiModelProperty("数据总数")
    private Long total;

    public static <T> RPage<T> ok() {
        return page(null, 0L);
    }

    public static <T> RPage<T> ok(IPage<?> page) {
        if (page == null) {
            return page(null, 0L);
        }
        RPage<T> r = new RPage<>();
        r.setCode(CommonConsts.SUCCESS);
        List<?> records = page.getRecords();
        @SuppressWarnings("unchecked")
        T data = (T) records;
        r.setData(data);
        r.setTotal(page.getTotal());
        r.setMessage(CommonConsts.SUCCESS_STR);
        return r;
    }

    public static <T> RPage<T> page(T data, long total) {
        RPage<T> r = new RPage<>();
        r.setCode(CommonConsts.SUCCESS);
        r.setData(data);
        r.setTotal(total);
        r.setMessage(CommonConsts.SUCCESS_STR);
        return r;
    }
}
